<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { userStore } from '@/store/userStore'
  /** 导入注册各种组件 */
  import RoomStatus from './components/room-status.vue'
  import { ref } from 'vue'
  import type { MsgData, MsgItem, OrderDetail } from '@/types/room'
  import { onLoad } from '@dcloudio/uni-app'
  import { orderDetailApi } from '@/apis/room'
  import { io, type Socket } from 'socket.io-client'
  import patientInfo from './components/patient-info.vue'
  import notifyInfo from './components/notify-info.vue'
  import messageInfo from './components/message-info.vue'
  import prescriptionInfo from './components/prescription-info.vue'
  import rateInfo from './components/rate-info.vue'
  import { uploadImageApi } from '@/apis/description'
  const props = defineProps<{ orderId: string; payResult: string }>()
  if (props.payResult === 'false') {
    uni.switchTab({
      url: '/pages/my/my',
    })
  }
  const orderDetail = ref({} as OrderDetail)
  const getOrderInfo = async (id: string) => {
    const data = await orderDetailApi(id)
    orderDetail.value = data
  }
  onLoad(async (e) => {
    const data = await orderDetailApi(e!['orderId'])
    orderDetail.value = data
  })
  const store = userStore()
  const socket: Socket = io('https://consult-api.itheima.net', {
    auth: { token: 'Bearer ' + store.token },
    query: { orderId: props.orderId },
    transports: ['websocket', 'polling'],
    timeout: 5000,
  })
// 
  socket.on('statusChange', (event) => {
    // 收到服务器发送的消息
    getOrderInfo(props.orderId)
  })

  const messageList = ref<MsgItem[]>([])
  socket.on('chatMsgList', (res: MsgData) => {
    // 收到服务器发送的消息
    if (res.code !== 10000) return
    // 提取列表数据
    res.data?.forEach(({ items }) => {
      // 追加到消息列表中
      messageList.value.push(...items!)
    })
  })
  socket.on('receiveChatMsg', (message: MsgItem) => {
    // 收到服务器发送的消息
    socket.emit('updateMsgStatus', message.id)
    // 追加到消息列表中
    messageList.value.push(message)
    console.log(JSON.stringify(messageList))
  })
  // 聊天信息
  const textMessage = ref('')
  // 发送文本
  const onInputConfirm = () => {
    console.log(
      'from',
      store.user.id,
      'to',
      orderDetail.value.docInfo?.id,
      'msg',
      textMessage.value
    )
    if (orderDetail.value.status !== 3) {
      return uni.showToast({
        title: '当前医生不在线!',
        icon: 'none',
      })
    }
    socket.emit('sendChatMsg', {
      from: store.user.id,
      to: orderDetail.value.docInfo?.id,
      msgType: 1,
      msg: {
        content: textMessage.value,
      },
    })
    textMessage.value = ''
  }

  const onImageButtonClick = async () => {
    if (orderDetail.value.status !== 3) {
      return uni.showToast({
        title: '当前医生不在线!',
        icon: 'none',
      })
    }
    const res = await uni.chooseImage()
    const fp = res.tempFilePaths[0]
    const picture = await uploadImageApi(fp)
    socket.emit('sendChatMsg', {
      from: store.user.id,
      to: orderDetail.value.docInfo?.id,
      msgType: 4,
      msg: {
        picture,
      },
    })
  }
</script>

<template>
  <view class="room-page">
    <RoomStatus
      :status="orderDetail.status"
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.status"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <template v-for="message in messageList" :key="message.id">
          <!-- 消息通知 -->
          <message-info v-if="message.msgType! <= 4" :info="message" :type="message.msgType!" />
          <!-- 系统通知 -->
          <notify-info v-if="message.msgType! >= 31" :type="message.msgType">
            {{ message.msg!.content }}
          </notify-info>
          <!-- 患者卡片 -->
          <patientInfo v-if="message.msgType === 21" :info="message.msg?.consultRecord!" />
          <!-- 处方消息 -->
          <prescriptionInfo v-if="message.msgType === 22" :info="message.msg!.prescription!" />
          <!-- 评价消息 -->
          <rateInfo
            v-if="message.msgType === 23 || message.msgType === 24"
            :type="message.msgType!"
            :order-id="props.orderId"
            :doctor-id="orderDetail.docInfo?.id!"
          />
        </template>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderDetail.status !== 3"
          :clearable="false"
          @confirm="onInputConfirm"
          v-model="textMessage"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="onImageButtonClick">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
